<!-- 角色权限分配弹窗 -->
<template>
  <RadModal
    width="60%"
    title="分配数据权限"
    :is-update="false"
    :visible="visible"
    :loading="loading"
    @visible-change="updateVisible"
    @ok="save"
  >
    <a-spin :spinning="authLoading">
      <div style="height: 60vh" class="ele-scrollbar-hover">
        <a-form ref="formRef" layout="vertical" :model="form">
          <a-form-item label="数据范围">
            <a-radio-group
              size="default"
              v-model:value="form.dataScope"
              button-style="solid"
              @change="(e:RadioChangeEvent)=>{
                InitOwnOrgData(e.target.value);
            }"
            >
              <a-radio-button value="1">全部数据</a-radio-button>
              <a-radio-button value="2">本部门及以下</a-radio-button>
              <a-radio-button value="3">本部门数据</a-radio-button>
              <a-radio-button value="4">仅本人数据</a-radio-button>
              <a-radio-button value="5">自定义数据</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-form>
        <a-tree
          v-if="form.dataScope == '5'"
          ref="treeAction"
          :checkable="true"
          :fieldNames="{ title: 'name', key: 'id' }"
          :tree-data="(authData as any)"
          v-model:checkedKeys="ownOrgData"
          @check="handleCheck"
        />
      </div>
    </a-spin>
  </RadModal>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import useFormData from '@/utils/use-form-data';
  import { grantRoleData, ownOrgList } from '@/api/system/role';
  import { listOrganizations } from '@/api/system/organization';
  import type { Role } from '@/api/system/role/model';
  import { FormInstance, RadioChangeEvent, TreeProps } from 'ant-design-vue';
  import RadModal from '@/components/RadModal/index.vue';

  interface RoleAuthData {
    id: number | undefined;
    dataScope: number | string | undefined;
    orgIdList: number[];
  }
  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 当前角色数据
    data?: Role | null;
  }>();
  const formRef = ref<FormInstance | null>(null);
  const treeAction = ref<TreeProps>({});
  // 表单数据
  const { form, resetFields } = useFormData<RoleAuthData>({
    id: 0,
    dataScope: '1',
    orgIdList: []
  });

  // 权限数据
  const authData = ref<any[]>([]);

  // 权限数据请求状态
  const authLoading = ref(false);

  // 提交状态
  const loading = ref(false);

  const ownOrgData = ref<any | undefined[]>([]);
  let checkKeys: number[] = []; // 子节点集合(勾选)

  /* 查询权限数据 */
  const query = () => {
    if (!props.data) {
      return;
    }
    authLoading.value = true;
    listOrganizations({})
      .then((data) => {
        authLoading.value = false;
        // 转成树形结构的数据
        authData.value = data as any[];
        form.id = props.data?.id;
        form.dataScope = props.data?.dataScope?.toString();
        console.log(props.data);
        InitOwnOrgData(form.dataScope);
      })
      .catch((e) => {
        authLoading.value = false;
        message.error(e.message);
      });
  };
  const InitOwnOrgData = async (dataScope) => {
    if (dataScope === '5') {
      ownOrgData.value = await ownOrgList(form.id);
      checkKeys = ownOrgData.value;
    } else {
      ownOrgData.value = [];
    }
  };

  // 节点勾选事件
  function handleCheck(_checkedKeys) {
    checkKeys = _checkedKeys;
  }

  /* 保存权限分配 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        console.log(checkKeys);

        form.orgIdList = checkKeys;
        grantRoleData(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((error) => {
            debugger;
            loading.value = false;
            message.error(error);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        query();
      } else {
        resetFields();
      }
    }
  );
</script>
